/* $Id: ContestScoreModel.java 129 2011-08-26 05:27:43Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models.scores;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.ContestEntry;
import alt.djudge.frontend.server.datatypes.scores.ContestScoreEntry;
import alt.djudge.frontend.server.models.AbstractBigtableModelCore;
import alt.djudge.frontend.server.models.AbstractDBModelCore;
import alt.djudge.frontend.server.models.ContestsModel;
import alt.djudge.frontend.server.models.CoreInterface;


public class ContestScoreModel
{
	private static CoreInterface<ContestScoreEntry> core = Deployment.isGAE() ?  
		new AbstractBigtableModelCore<ContestScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ContestScoreEntry> getEntryClass()
			{
				return ContestScoreEntry.class;
			}
		}
	:
		new AbstractDBModelCore<ContestScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ContestScoreEntry> getEntryClass()
			{
				return ContestScoreEntry.class;
			}
		};		
	
	public static List<ContestScoreEntry> getAllEntries()
	{
		List<ContestScoreEntry> list = core.getAllEntries();
		return list;
	}

	public static ContestScoreEntry getContestEntry(Long contestId)
	{
		ContestScoreEntry entry = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("contestId", contestId);
		List<ContestScoreEntry> list = core.getEntries(map);
		if (list.size() > 0)
		{
			entry = list.get(0);
		}
		else
		{
			entry = new ContestScoreEntry(contestId);
			entry.makePersistent();
		}
		return entry;
	}

	public static List<ContestScoreEntry> getContestEntries(Long contestId)
	{
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("contestId", contestId);
		List<ContestScoreEntry> list = core.getEntries(map);
		return list;		
	}
	
	public static Map<Long, ContestScoreEntry> getEntriesMap()
	{
		HashMap<Long, ContestScoreEntry> map = new HashMap<Long, ContestScoreEntry>();
		List<ContestEntry> contestEntries = ContestsModel.getAllEntries();
		for (ContestEntry contestEntry : contestEntries)
			map.put(contestEntry.getId(), getContestEntry(contestEntry.getId()));
		return map;
	}
	
	public static void deleteAllEntries()
	{
		core.deleteAllEntries();
	}	
}
